const express = require('express');
const {
  Rule
} = require('../models');
const {
  Op
} = require('sequelize');
const router = express.Router();
router.get('/rule', async (req, res) => {
  const current = parseInt(req.query.current);
  const pageSize = parseInt(req.query.pageSize);
  let whereClause = {};
  if (req.query.name) {
    whereClause.name = {
      [Op.like]: `%${req.query.name}%`
    };
  }
  if (req.query.desc) {
    whereClause.desc = {
      [Op.like]: `%${req.query.desc}%`
    };
  }
  if (req.query.filterField && req.query.filterValues) {
    const filterFields = req.query.filterField.split(',');
    const filterValuesList = req.query.filterValues.split(';').map(val => val.split(','));
    filterFields.forEach((field, index) => {
      whereClause[field] = {
        [Op.in]: filterValuesList[index]
      };
    });
  }
  let orderClause = [];
  if (req.query.sortField && req.query.sortOrder) {
    const fields = req.query.sortField.split(',');
    const orders = req.query.sortOrder.split(',').map(order => order === 'ascend' ? 'ASC' : 'DESC');
    orderClause = fields.map((field, index) => [field, orders[index]]);
  }
  try {
    const total = await Rule.count({
      where: whereClause
    });
    const rules = await Rule.findAll({
      where: whereClause,
      limit: pageSize,
      offset: (current - 1) * pageSize,
      order: orderClause
    });
    res.status(200).json({
      data: rules,
      total: total,
      success: true,
      pageSize: pageSize,
      current: current
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      success: false,
      message: 'Error retrieving rules'
    });
  }
});
router.post('/rule', async (req, res) => {
  try {
    const rule = await Rule.create(req.body);
    res.json(rule);
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: 'Error creating rule'
    });
  }
});
router.put('/rule', async (req, res) => {
  try {
    let {
      key,
      ...rule
    } = req.body;
    const updatedRule = await Rule.update(rule, {
      where: {
        key
      }
    });
    if (updatedRule[0] === 0) {
      return res.status(404).json({
        message: 'Rule not found'
      });
    }
    res.json({
      success: true
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: 'Error updating rule'
    });
  }
});
router.delete('/rule', async (req, res) => {
  try {
    console.log(req.body);
    const rowsDeleted = await Rule.destroy({
      where: {
        key: req.body.key
      }
    });
    if (rowsDeleted === 0) {
      return res.status(404).json({
        message: 'Rule not found'
      });
    }
    res.json({
      success: true
    });
  } catch (err) {
    res.status(500).json({
      message: 'Error deleting rule'
    });
  }
});
module.exports = router;